package com.example.controller;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.example.common.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import cn.hutool.core.io.FileUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/files")
public class FileController {

    @Value("${server.port}")//取端口号
    private String port;
    private static final String ip = "http://localhost";

    @PostMapping("/upload")
    public Result upload(MultipartFile file){
        String originalFilename = file.getOriginalFilename();//源文件名
        String flag = IdUtil.fastSimpleUUID();//唯一前缀,uuid+原名
        String rootFilePath = System.getProperty("user.dir") + "scholarship-backend/src/main/resources/file" + flag + "_" + originalFilename;//上传路径
        try {
            FileUtil.writeBytes(file.getBytes(),rootFilePath);//写入上传路径
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Result.success(ip + ":" + port + "/file/" + flag);//1M以下不然报错
    }//上传


    @GetMapping("/{flag}")
    public void getFile(@PathVariable String flag, HttpServletResponse response){
        OutputStream os;//输出流对象
        String basePath = System.getProperty("user.dir") + "/src/main/resources/file/";//上传根路径找
        List<String> fileNames = FileUtil.listFileNames(basePath);//获取文件名
        String fileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");
        try{
            if(StrUtil.isNotEmpty(fileName)){
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(basePath + fileName);//通过路径读取文件字节流
                os = response.getOutputStream();//输出流返回文件
                os.write(bytes);
                os.flush();
                os.close();
            }
        }catch(Exception e){
            System.out.println("文件下载失败");//路径里不存在
        }
    }//下载

}